package com.un.ebs.product.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import com.un.ebs.product.domain.ProductCanSaleExt;
import com.un.ebs.product.domain.ProductExt;
import com.un.ebs.product.domain.ProductOrderCommentExt;
import com.un.ebs.product.dto.*;
import com.un.ebs.product.excel.BomDetailDto;
import com.un.ebs.product.excel.BomDetailListener;
import com.un.ebs.product.mapper.ProductCanSaleExtMapper;
import com.un.ebs.product.service.ProductClassAttrService;
import com.un.ebs.product.service.ProductService;
import com.un.ebs.sys.dto.ObjectParentAndIndexChangeDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-16
 */
@RestController
@RequestMapping("/product")
@Api(value = "product", description = "商品spu")
public class ProductController {

    @Autowired
    private ProductService service;

    @Autowired
    private ProductCanSaleExtMapper productCanSaleExtMapper;

    @Autowired
    private ProductClassAttrService productClassAttrService;

    @PostMapping("save")
    @ApiOperation(value = "save", notes = "修改商品信息，并由该函数管理 SKU 的重建和修改逻辑")
    public WebResult save(@RequestBody @Validated ProductDto req) {
        if (StringUtils.isNullOrEmpty(req.getId())) {
            service.add(req);
        } else {
            service.update(req);
        }
        return WebUtils.success();
    }

    @PostMapping("addBatch")
    @ApiOperation("批量添加商品SPU")
    public WebResult addBatch(@RequestBody List<ProductDto> req) {
        service.add(req);
        return WebUtils.success();
    }

    @PostMapping("addItem")
    @ApiOperation("往SPU中所有的SKu添加包含的子SKU")
    public WebResult addInclude(@RequestParam @Validated String spuId, @RequestParam String includeSkuId, @RequestParam Double qty) {
        service.addInclude(spuId, includeSkuId, qty);
        return WebUtils.success();
    }

    @PostMapping("inputData")
    @ApiOperation("往SPU中所有的SKu添加包含的子SKU")
    public WebResult inputData(@RequestParam(value = "file") MultipartFile file,
                               @RequestParam(value = "classId", required = false) String classId) {

        try {
            EasyExcel.read(file.getInputStream(), BomDetailDto.class, new BomDetailListener(service, classId)).doReadAll();
        } catch (IOException e) {
            return WebUtils.error(e);
        }
        return WebUtils.success();
    }

    @PostMapping("clearItem")
    @ApiOperation("清除SPU下所有SKU的子SKU")
    public WebResult clearInclude(@RequestParam String spuId) {
        service.clearInclude(spuId);
        return WebUtils.success();
    }

    @PostMapping("updateBatch")
    @ApiOperation("批量修改商品SPU")
    public WebResult updateBatch(@RequestBody @Validated ProductBatchUpdateDto req) {
        service.updateBatch(req);
        return WebUtils.success();
    }

    @PostMapping("changeSort")
    @ApiOperation("修改商品排序")
    public WebResult changeSort(@RequestBody List<ObjectParentAndIndexChangeDto> req) {
        service.changeSort(req);
        return WebUtils.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据主键获取单个 Product")
    public WebResult<ProductVo> getById(@PathVariable("id") String id) {
        return WebUtils.success(service.queryViewById(id));
    }

    @GetMapping("detail/{id}")
    @ApiOperation("根据主键获取单个 Product，不需要认证")
    public WebResult<ProductVo> getViewById(@PathVariable("id") String id) {
        return WebUtils.success(service.queryViewById(id));
    }

    @GetMapping("list")
    @ApiOperation(value = "查询SPU集合")
    public WebResult<IPage<ProductExt>> list(@RequestParam(required = false)
                                             @ApiParam("类别ID，递归查询") String classId,
                                             @RequestParam(required = false)
                                             @ApiParam("支持商品编码、商品名称、商品描述字段") String searchText,
                                             @RequestParam(required = false)
                                             @ApiParam("是否只查询上架商品，如果为否，则查询所有，default: false") Boolean onlyCanSale,
                                             @RequestParam(required = false)
                                             @ApiParam("default: 10") Integer pageSize,
                                             @RequestParam(required = false)
                                             @ApiParam("default: 1") Integer pageIndex) {
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageIndex == null) {
            pageIndex = 1;
        }
        return WebUtils.success(service.query(classId, searchText, onlyCanSale, pageSize, pageIndex));
    }

    @PostMapping("listBySaleClass")
    @ApiOperation(value = "查询，根据前台销售类别")
    public WebResult<IPage<ProductExt>> queryBySaleClass(@RequestBody ProductQueryBySaleClassRequest req) {
        return WebUtils.success(service.queryBySaleClass(req));
    }

    @PostMapping("listPage")
    @ApiOperation(value = "查询SPU集合")
    public WebResult<IPage<ProductExt>> listPage(@RequestBody ProductQueryRequest req) {
        return WebUtils.success(service.query(req));
    }

    @GetMapping("listQueryAttr")
    @ApiOperation(value = "获取动态查询条件")
    public WebResult<List<ProductQueryAttrResponse>> listQueryAttr(@RequestParam String classId) {
        return WebUtils.success(service.queryQueryAttr(classId));
    }

    @GetMapping("listColumnAttr")
    @ApiOperation(value = "获取动态查询条件")
    public WebResult<List<ProductQueryAttrResponse>> listColumnAttr(@RequestParam String classId) {
        return WebUtils.success(service.queryColumnAttr(classId));
    }

    @GetMapping("listOrderRec")
    @ApiOperation("根据商品ID查询所有订单记录")
    public WebResult<List<ProductOrderRecDto>> listOrderRec(@RequestParam String productId) {
        return WebUtils.success(service.queryOrderRec(productId));
    }

    @GetMapping("listOrderRecPage")
    @ApiOperation("根据商品ID查询所有订单记录")
    public WebResult<Page<ProductOrderRecDto>> listOrderPage(@RequestParam String productId, @RequestParam(required = false) Integer pageIndex, @RequestParam(required = false) Integer pageSize) {
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        return WebUtils.success(service.queryOrderRec(productId, pageIndex, pageSize));
    }

    @GetMapping("listComment")
    @ApiOperation("根据商品ID查询所有留言记录")
    public WebResult<IPage<ProductOrderCommentExt>> listComment(@RequestParam String productId, @RequestParam int pageIndex, int pageSize) {
        return WebUtils.success(service.queryComment(productId, pageIndex, pageSize));
    }

//    @GetMapping("listPage")
//    @ApiOperation(value = "listPage", notes = "")
//    public WebResult<IPage<ProductExt>> listPage(@RequestParam String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
//        return WebUtils.success(service.query(null, searchText, false, pageSize, pageIndex));
//    }

    @GetMapping("listPageByClass")
    @ApiOperation(value = "listPageByClass", notes = "")
    public WebResult<IPage<ProductExt>> listPageByClass(@RequestParam @ApiParam("类别ID") String classId, @RequestParam String searchText, @RequestParam int
            pageSize, @RequestParam int
                                                                pageIndex) {
        return WebUtils.success(service.query(classId, searchText, false, pageSize, pageIndex));
    }

    @GetMapping("listCanBook")
    @ApiOperation(value = "查询支持预约的商品")
    public WebResult<List<ProductExt>> listCanBook() {
        return WebUtils.success(service.queryCanBook());
    }

    @GetMapping("listDeleted")
    @ApiOperation(value = "查询，已删除的商品")
    public WebResult<List<ProductExt>> listDeleted(@RequestParam String code, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryDeleted(StringUtils.isNullOrEmpty(code) ? null : code.trim(), pageSize, pageIndex));
    }

    @Deprecated
    @GetMapping("listCanSale")
    @ApiOperation(value = "listCanSale", notes = "可售前商品查询--应改为SKU和打包品列表")
    public WebResult<IPage<ProductCanSaleExt>> listCanSale(@RequestParam(value = "classId", required = false) @ApiParam("类别ID，递归查询") String classId, @RequestParam(value = "searchText", required = false) String searchText, @RequestParam("pageSize") Integer pageSize, @RequestParam("pageIndex") Integer pageIndex) {
        Page<ProductCanSaleExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<ProductCanSaleExt> wrapper = Wrappers.lambdaQuery();

        if (!StringUtils.isNullOrEmpty(classId)) {
            List<String> ids = productClassAttrService.queryClassChildIds(classId);
            if (ids.size() > 0) {
                wrapper.in(ProductCanSaleExt::getClassId, ids);
            } else {
                wrapper.eq(ProductCanSaleExt::getClassId, classId);
            }
        }
        if (!StringUtils.isNullOrEmpty(searchText)) {
            wrapper.and(obj -> obj
                    .like(ProductCanSaleExt::getCode, searchText).or()
                    .like(ProductCanSaleExt::getName, searchText));
        }
        wrapper.orderByAsc(ProductCanSaleExt::getName);
        return WebUtils.success(productCanSaleExtMapper.selectPage(page, wrapper));
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "delete", notes = "根据主键删除单个 Product")
    public WebResult delete(@PathVariable("id") String id) {
        service.delete(id);
        return WebUtils.success();
    }

    @PostMapping("unDelete/{id}")
    @ApiOperation(value = "unDelete", notes = "根据主键删除单个 Product")
    public WebResult unDelete(@PathVariable("id") String id) {
        service.unDelete(id);
        return WebUtils.success();
    }

    @PostMapping("updateSku/{productId}")
    @ApiOperation(value = "updateSku")
    public WebResult updateSku(@PathVariable("productId") String productId) {
        service.updateSku(productId);
        return WebUtils.success();
    }

    @PostMapping("upperShelf/{productId}")
    @ApiOperation(value = "upperShelf", notes = "上线销售")
    public WebResult upperShelf(@PathVariable("productId") String productId) {
        service.upperShelf(productId);
        return WebUtils.success();
    }

    @PostMapping("lowerShelf/{productId}")
    @ApiOperation(value = "lowerShelf", notes = "商品下架")
    public WebResult lowerShelf(@PathVariable("productId") String productId) {
        service.lowerShelf(productId);
        return WebUtils.success();
    }

    @PostMapping("updateQualityProportion/{productId}")
    @ApiOperation(value = "updateQualityProportion", notes = "")
    public WebResult updateQualityProportion(@PathVariable("productId") String productId, @RequestParam Double purchaseQualityProportion, @RequestParam Double saleQualityProportion, @RequestParam Double productionQualityProportion) {
        service.updateQualityProportion(productId, purchaseQualityProportion, saleQualityProportion, productionQualityProportion);
        return WebUtils.success();
    }

}